package com.hjy.backend.tableManager;

import com.google.common.primitives.Bytes;
import com.hjy.backend.parser.statement.*;
import com.hjy.backend.tableManager.result.FieldCalRes;
import com.hjy.backend.transactionManager.TransactionManagerImpl;
import com.hjy.common.error.Error;
import com.hjy.backend.utils.Panic;
import com.hjy.backend.utils.ParseStringRes;
import com.hjy.backend.utils.Parser;


import java.util.*;

/**
 * Table 维护了表结构
 * 二进制结构如下：
 * [TableName][NextTable]
 * [Field1Uid][Field2Uid]...[FieldNUid]
 * <p>
 * TableName 是string类型: [StringLength][StringData], 前4位是string的长度, 后面是str字符串
 * NextTable, Field1Uid 等等都是 8 位
 */
public class Table {
    TableManager tbm;
    long uid; // 对应的 dataItem
    String name; // 表名
    byte status;
    long nextUid; // 下一个表的 uid
    List<Field> fields = new ArrayList<>();

    /**
     * 根据uid加载表
     *
     * @param tbm
     * @param uid
     * @return
     */
    public static Table loadTable(TableManager tbm, long uid) {
        byte[] raw = null;
        try {
            raw = ((TableManagerImpl)tbm).vm.read(TransactionManagerImpl.SUPER_XID, uid);
        } catch (Exception e) {
            Panic.panic(e);
        }
        assert raw != null;
        Table tb = new Table(tbm, uid);
        // 解析表
        return tb.parseSelf(raw);
    }


    /**
     * 创建表, 并且持久化
     *
     * @param tbm
     * @param nextUid
     * @param xid
     * @param create
     * @return
     * @throws Exception
     */
    public static Table createTable(TableManager tbm, long nextUid, long xid, Create create) throws Exception {
        //
        Table tb = new Table(tbm, create.tableName, nextUid);
        // 塞以下字段
        for (int i = 0; i < create.fieldName.length; i++) {
            String fieldName = create.fieldName[i];
            String fieldType = create.fieldType[i];
            boolean indexed = false;
            // 看这个字段是否是索引
            for (int j = 0; j < create.index.length; j++) {
                if (fieldName.equals(create.index[j])) {
                    indexed = true;
                    break;
                }
            }
            tb.fields.add(Field.createField(tb, xid, fieldName, fieldType, indexed));
        }

        return tb.persistSelf(xid);
    }

    public Table(TableManager tbm, long uid) {
        this.tbm = tbm;
        this.uid = uid;
    }

    public Table(TableManager tbm, String tableName, long nextUid) {
        this.tbm = tbm;
        this.name = tableName;
        this.nextUid = nextUid;
    }

    /**
     * 根据字节数组解析表和其所有字段, 下一张表UID
     *
     * @param raw
     * @return
     */
    private Table parseSelf(byte[] raw) {
        int position = 0;
        // 首先解析表名
        ParseStringRes res = Parser.parseString(raw);
        name = res.str;
        position += res.next;
        // 解析下一张表的UID
        nextUid = Parser.parseLong(Arrays.copyOfRange(raw, position, position + 8));
        position += 8;

        // 解析出表所有的字段
        while (position < raw.length) {
            long uid = Parser.parseLong(Arrays.copyOfRange(raw, position, position + 8));
            position += 8;
            fields.add(Field.loadField(this, uid));
        }
        return this;
    }

    /**
     * 根据表二进制格式, 持久化存储
     *
     * @param xid
     * @return
     * @throws Exception
     */
    private Table persistSelf(long xid) throws Exception {
        byte[] nameRaw = Parser.string2Byte(name);
        byte[] nextRaw = Parser.long2Byte(nextUid);
        byte[] fieldRaw = new byte[0];
        for (Field field : fields) {
            fieldRaw = Bytes.concat(fieldRaw, Parser.long2Byte(field.uid));
        }
        uid = ((TableManagerImpl) tbm).vm.insert(xid, Bytes.concat(nameRaw, nextRaw, fieldRaw));
        return this;
    }

    /**
     * 删除语句 sql
     *
     * @param xid    事务号
     * @param delete
     * @return 返回删除的行数
     * @throws Exception
     */
    public int delete(long xid, Delete delete) throws Exception {
        // 要删除的哪些记录
        List<Long> uids = parseWhere(delete.where);
        int count = 0;
        for (Long uid : uids) {
            // 删除记录
            if (((TableManagerImpl) tbm).vm.delete(xid, uid)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 修改语句 sql
     *
     * @param xid    事务号
     * @param update
     * @return
     * @throws Exception
     */
    public int update(long xid, Update update) throws Exception {
        // 找到哪些行需要被修改
        List<Long> uids = parseWhere(update.where);
        Field fd = null;
        // 找到需要修改的字段
        for (Field f : fields) {
            if (f.fieldName.equals(update.fieldName)) {
                fd = f;
                break;
            }
        }
        if (fd == null) {
            throw Error.FieldNotFoundException;
        }
        // 修改后的值
        Object value = fd.string2Value(update.value);
        int count = 0;
        for (Long uid : uids) {
            // 读出记录的位置
            byte[] raw = ((TableManagerImpl) tbm).vm.read(xid, uid);
            if (raw == null) continue;

            // 先删除这个记录
            ((TableManagerImpl) tbm).vm.delete(xid, uid);
            // 将旧的数据解析成 字段名:字段值的形式
            Map<String, Object> entry = parseEntry(raw);
            // 装载修改后的值
            entry.put(fd.fieldName, value);
            // 新的数据
            raw = entry2Raw(entry);
            // 插入, 返回新记录的 uid
            long uuid = ((TableManagerImpl) tbm).vm.insert(xid, raw);

            count++;

            for (Field field : fields) {
                if (field.isIndexed()) {
                    // 如果修改的字段是索引. 那么我们需要插入B+tree, 其中字段名是该行记录对应的字段名的值
                    field.insert(entry.get(field.fieldName), uuid);
                }
            }
        }
        return count;
    }

    /**
     * select语句 sql
     *
     * @param xid
     * @param read
     * @return
     * @throws Exception
     */
    public String read(long xid, Select read) throws Exception {
        // 哪些语句
        List<Long> uids = parseWhere(read.where);
        StringBuilder sb = new StringBuilder();
        for (Long uid : uids) {
            // 根据xid可见性查看是否看得见
            byte[] raw = ((TableManagerImpl) tbm).vm.read(xid, uid);
            if (raw == null) continue;
            // 字段名:字段值
            Map<String, Object> entry = parseEntry(raw);
            // 表的一样的字符结构
            sb.append(printEntry(entry)).append("\n");
        }
        return sb.toString();
    }

    /**
     * insert语句 sql
     *
     * @param xid
     * @param insert
     * @throws Exception
     */
    public void insert(long xid, Insert insert) throws Exception {
        Map<String, Object> entry = string2Entry(insert.values);
        byte[] raw = entry2Raw(entry);
        long uid = ((TableManagerImpl) tbm).vm.insert(xid, raw);
        for (Field field : fields) {
            if (field.isIndexed()) {
                field.insert(entry.get(field.fieldName), uid);
            }
        }
    }

    /**
     * 将字符串数组解析成 字段名: 字段值的Map结构
     *
     * @param values
     * @return
     * @throws Exception
     */
    private Map<String, Object> string2Entry(String[] values) throws Exception {
        if (values.length != fields.size()) {
            throw Error.InvalidValuesException;
        }
        Map<String, Object> entry = new HashMap<>();
        for (int i = 0; i < fields.size(); i++) {
            Field f = fields.get(i);
            Object v = f.string2Value(values[i]);
            entry.put(f.fieldName, v);
        }
        return entry;
    }

    /**
     * 解析where语句
     *
     * @param where
     * @return 受影响的行的 uid 列表
     * @throws Exception
     */
    private List<Long> parseWhere(Where where) throws Exception {
        long l0 = 0, r0 = 0, l1 = 0, r1 = 0;
        boolean single = false;
        Field fd = null;
        if (where == null) {
            // 没有 where语句, 就找出第一个索引字段
            for (Field field : fields) {
                if (field.isIndexed()) {
                    fd = field;
                    break;
                }
            }
            l0 = 0;
            r0 = Long.MAX_VALUE;
            single = true;
        } else {
            for (Field field : fields) {
                if (field.fieldName.equals(where.singleExp1.field)) {
                    // where 语句中的字段必须是索引字段
                    if (!field.isIndexed()) {
                        throw Error.FieldNotIndexedException;
                    }
                    fd = field;
                    break;
                }
            }
            if (fd == null) {
                throw Error.FieldNotFoundException;
            }
            // 逻辑计算, 获取记录key的范围
            CalWhereRes res = calWhere(fd, where);
            l0 = res.l0;
            r0 = res.r0;
            l1 = res.l1;
            r1 = res.r1;
            single = res.single;
        }
        // 查找所有记录的uid
        List<Long> uids = fd.search(l0, r0);
        // 有 and or 这些逻辑
        if (!single) {
            List<Long> tmp = fd.search(l1, r1);
            uids.addAll(tmp);
        }
        return uids;
    }

    class CalWhereRes {
        long l0, r0, l1, r1;
        boolean single;
    }

    /**
     * 获取uid key的范围
     *
     * @param fd
     * @param where
     * @return
     * @throws Exception
     */
    private CalWhereRes calWhere(Field fd, Where where) throws Exception {
        CalWhereRes res = new CalWhereRes();
        switch (where.logicOp) {
            case "":
                res.single = true;
                FieldCalRes r = fd.calExp(where.singleExp1);
                res.l0 = r.left;
                res.r0 = r.right;
                break;
            case "or":
                res.single = false;
                r = fd.calExp(where.singleExp1);
                res.l0 = r.left;
                res.r0 = r.right;
                r = fd.calExp(where.singleExp2);
                res.l1 = r.left;
                res.r1 = r.right;
                break;
            case "and":
                res.single = true;
                r = fd.calExp(where.singleExp1);
                res.l0 = r.left;
                res.r0 = r.right;
                r = fd.calExp(where.singleExp2);
                res.l1 = r.left;
                res.r1 = r.right;
                if (res.l1 > res.l0) res.l0 = res.l1;
                if (res.r1 < res.r0) res.r0 = res.r1;
                break;
            default:
                throw Error.InvalidLogOpException;
        }
        return res;
    }

    /**
     * 输出为行结构
     *
     * @param entry
     * @return
     */
    private String printEntry(Map<String, Object> entry) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < fields.size(); i++) {
            Field field = fields.get(i);
            sb.append(field.printValue(entry.get(field.fieldName)));
            if (i == fields.size() - 1) {
                sb.append("]");
            } else {
                sb.append(", ");
            }
        }
        return sb.toString();
    }

    /**
     * 解下成 字段名: 字段值的形式
     *
     * @param raw
     * @return
     */
    private Map<String, Object> parseEntry(byte[] raw) {
        int pos = 0;
        Map<String, Object> entry = new HashMap<>();
        for (Field field : fields) {
            Field.ParseValueRes r = field.parserValue(Arrays.copyOfRange(raw, pos, raw.length));
            entry.put(field.fieldName, r.v);
            pos += r.shift;
        }
        return entry;
    }

    /**
     * 将 字段名: 字段值装载成字节数组
     *
     * @param entry
     * @return
     */
    private byte[] entry2Raw(Map<String, Object> entry) {
        byte[] raw = new byte[0];
        for (Field field : fields) {
            raw = Bytes.concat(raw, field.value2Raw(entry.get(field.fieldName)));
        }
        return raw;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("{");
        sb.append(name).append(": ");
        for (Field field : fields) {
            sb.append(field.toString());
            if (field == fields.get(fields.size() - 1)) {
                sb.append("}");
            } else {
                sb.append(", ");
            }
        }
        return sb.toString();
    }
}
